from urllib.request import  urlopen
from urllib.parse import  urlencode
import json
import  requests

#代码发get请求
url="http://127.0.0.1:8888/get?name=abbb"
req=urlopen(url)
result=json.loads(req.read().decode())
print(result)


#post请求
url="http://127.0.0.1:8888/get"
data={"name":"post"}
req=urlopen(url,urlencode((data).encode()))
print(req.read().decode())

#发get请求
#作为客户端调用某个接口后的返回值
url="http://127.0.0.1:8888/get"
data={"name":"哈哈哈哈"}
req=requests.get(url=url,params=data)




#发post请求,接口需要支持post方法
#作为客户端调用某个接口后的返回值
url="http://127.0.0.1:8888/get"
data={"name":"哈哈哈哈"}
req=requests.get(url=url,data=data)
#params=xxx，参数是传在url后面的
#data=xxx，参数是传在body里面的form-data里面的


#header、cookie接口调用
url="http://127.0.0.1:8888/header"
req=requests.post(url,headers={"hhhh":"232323","cookie":"time=ewe28392839"})

#json入参类型接口调用
url="http://127.0.0.1:8888/json"
data = {"age":36,"name":"哈哈哈哈","sex":1111}
req=requests.post(url,json=data)

#文件上传接口调用
url = "http://127.0.0.1:8888/file"
files = {"file":open("/Users/wangxiaoyan60/PycharmProjects/wangxiaoyan-homework/day7/wxy.log",'rb')}
req = requests.post(url,files=files)

#文件下载接口调用
url="https://q4.qlogo.cn/g?b=qq&nk=1357396742&s=140"
req=requests.get(url)
with open("lby.jpg",'wb') as fw:
    fw.write(req.content)

print(req.json())#直接把返回的数据转成字典
print(req.text)#返回的是字符串
print(req.content)#返回的是bytes类型的
print(req.cookies)#返回的cookie
print(req.status_code)#返回的http状态码
print(req.headers)#响应头





#叮叮发消息实例
#第一种关键字安全认证
# url = "https://oapi.dingtalk.com/robot/send?access_token=ea67b3129ba5b6d54b186af690023b0290800075d6dfa46caf8eca68fca5ccb7"
# headers={
#     "msgtype": "text",
#     "text": {
#         "content": "chifan,来吧月会通知"
#     }
# }
# req = requests.post( url, json=headers)


#第二种加签方式
import hmac
import hashlib
import base64
import urllib.parse

def get_sign():
    timestamp = str(round(time.time() * 1000))
    secret = 'SEC12e01f60fb742c3e63b1f45b636bf3246cb566a521dc9d70f70ba9e8d57261c9'
    secret_enc = secret.encode()
    string_to_sign = timestamp + '\n' + secret
    string_to_sign_enc = string_to_sign.encode()
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp,sign

import time
url = "https://oapi.dingtalk.com/robot/send?access_token=ea67b3129ba5b6d54b186af690023b0290800075d6dfa46caf8eca68fca5ccb7"

for i in range(1):
    data = {
        "msgtype": "text",
        "text": {
            "content": "我是万术成，我要吃饭 %s" % i
        },
        "at": {
            "atMobiles": [
                "18612532945",
                "18301040835",
            ],
            "isAtAll": False
        }
    }
    timestamp,sign = get_sign()
    params = {"timestamp":timestamp,'sign':sign}
    r = requests.post(url,json=data,params=params)
    print(r.json())
    time.sleep(1)


